package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    
    @Autowired
    private TokenService tokenService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        //判断是否是静态资源访问
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        //获取token
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)) {
            throw new BaseException("认证失败");
        }
        //解析token
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException("认证失败");
        }
        //获取token中的数据
        //Long userId = (Long) claims.get("userId");
        Long userId = MapUtil.get(claims, "userId", Long.class);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BaseException("认证失败");
        }
        //存储到threadLocal中
        UserThreadLocal.set(userId);
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理threadLocal中存储的数据
        UserThreadLocal.remove();
    }
}
